package com.ipoint.rusdf;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Simple wrapper around {@link SimpleDateFormat}. Makes it possible to get correctly ended month names in dates.
 * 
 * @author Konstantin Burov
 */
public class RussianDateFormat extends SimpleDateFormat {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5435727371895699693L;

	public RussianDateFormat(String format) {
		super(format, new Locale("ru"));
	}

	private String formatEndings(String month) {
		return month.replaceAll("[ьй]", "я").replaceAll("рт", "рта").replaceAll("ст", "ста").toLowerCase();
	}
	
	private String unformatEndings(String month) {
		return month.replaceAll("та", "т").replaceAll("ря", "рь").replaceAll("ля", "ль").replaceAll("ая", "ай")
				.toLowerCase();
	}
	
	public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
		return new StringBuffer(formatEndings(super.format(date, toAppendTo, pos).toString()));
	}
	
	public Date parse(String text, ParsePosition pos) {
		text = unformatEndings(text);
		Date formatted = super.parse(text, pos);
		return formatted;
	}
}